package com.hethongviet.vending.helper.db;

import java.util.ArrayList;
import java.util.List;

import com.hethongviet.vending.Utils;
import com.hethongviet.vending.model.BoxInventory;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class BoxInventorySQLite
{
	public static final String TABLE_NAME = "box_inventory";

	public static final String COLUMN_ID_DB = "idDB";

	public static final String COLUMN_ID_BOX = "IDBox";
	public static final String COLUMN_PRODUCT_CODE = "ProductID";
	public static final String COLUMN_PRODUCT_AMOUNT = "product_count";
	public static final String COLUMN_IS_SENT_SERVER_OK = "sent_server";
	public static final String COLUMN_DATE = "date";

	// Database fields
	private SQLiteDatabase _database;
	private MySQLiteHelper _dbHelper;
	private String[] _allColumns = { COLUMN_ID_DB, COLUMN_ID_BOX,

	COLUMN_PRODUCT_AMOUNT, COLUMN_IS_SENT_SERVER_OK, COLUMN_PRODUCT_CODE,
			COLUMN_DATE };

	public static final String STRING_COLUMNS = COLUMN_ID_DB
			+ " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, "
			+ COLUMN_ID_BOX + " integer, " + COLUMN_PRODUCT_AMOUNT
			+ " integer, " + COLUMN_IS_SENT_SERVER_OK + " integer, "
			+ COLUMN_PRODUCT_CODE + " text, " + COLUMN_DATE + " integer";

	public BoxInventorySQLite(Context context)
	{
		_dbHelper = new MySQLiteHelper(context, null, null);
	}

	public void open() throws SQLException
	{
		_database = _dbHelper.getWritableDatabase();
	}

	public void close()
	{
		_dbHelper.close();
	}

	private boolean dataExist(BoxInventory boxInventory, Cursor cursor)
	{
		if (cursor == null)
		{
			return false;
		}
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
		{
			long idDB = cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB));
			if (idDB == boxInventory.getIdDB()) return true;
		}
		return false;
	}

	/**
	 * @param boxInventory
	 * @return row id -1: insert fail
	 */
	public long insert(BoxInventory boxInventory)
	{
		Utils.debug("insert -- box inventory : " + boxInventory.getIdBox());
		open();

		Cursor cursor = _database.rawQuery("SELECT * FROM " + TABLE_NAME
				+ " WHERE " + COLUMN_ID_DB + " = " + boxInventory.getIdDB(),
				null);

		long temp = -1;
		if (!dataExist(boxInventory, cursor))
		{
			Utils.debug("insert 1111111111111 INSERT");
			/* Insert to database */
			/* Insert new */
			Cursor cursorInsert = _database.rawQuery(
					"INSERT INTO " + TABLE_NAME + "("

					+ COLUMN_ID_BOX + ", "

					+ COLUMN_PRODUCT_AMOUNT + ", " + COLUMN_PRODUCT_AMOUNT
							+ ", " + COLUMN_PRODUCT_CODE + ", " + COLUMN_DATE
							+ ") values( ?, ?, ?, ?, ?)",

					new String[] { boxInventory.getIdBox() + "",
							boxInventory.getProductAmount() + "",
							boxInventory.isSentServerOk() ? "1" : "0",
							boxInventory.getProductCode(),
							boxInventory.getDate() + "" });

			cursorInsert.moveToFirst();
			if (!cursorInsert.isAfterLast()) temp = cursorInsert
					.getLong(cursorInsert.getColumnIndex(COLUMN_ID_DB));

			cursorInsert.close();
		}
		else
		{
			Utils.debug("insert 1111111111111 update");

			ContentValues contentValues = new ContentValues();
			contentValues.put(COLUMN_ID_BOX, boxInventory.getIdBox());
			contentValues.put(COLUMN_PRODUCT_AMOUNT,
					boxInventory.getProductAmount());
			contentValues.put(COLUMN_IS_SENT_SERVER_OK,
					boxInventory.isSentServerOk() ? "1" : "0");
			contentValues.put(COLUMN_PRODUCT_CODE,
					boxInventory.getProductCode());
			contentValues.put(COLUMN_DATE, boxInventory.getDate());

			temp = _database.update(TABLE_NAME, contentValues, COLUMN_ID_DB
					+ " = " + boxInventory.getIdDB(), null);
		}
		cursor.close();
		close();
		return temp;
	}

	public void deleteAll()
	{
		open();

		System.out.println("project deleted all");
		// _database.rawQuery("DELETE FROM " + TABLE_NAME, null); not work
		// _database.rawQuery("DELETE FROM " + TABLE_NAME + " WHERE 1", null);
		_database.delete(TABLE_NAME, "1", null);
		close();
	}

	public List<BoxInventory> getAll()
	{
		open();

		List<BoxInventory> listBoxInventories = new ArrayList<BoxInventory>();

		Cursor cursor = _database.query(TABLE_NAME, _allColumns, null, null,
				null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast())
		{
			BoxInventory boxInventory = cursorToInventory(cursor);
			listBoxInventories.add(boxInventory);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		close();
		return listBoxInventories;
	}

	private BoxInventory cursorToInventory(Cursor cursor)
	{
		BoxInventory boxInventory = new BoxInventory();
		boxInventory
				.setIdDB(cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB)));

		boxInventory.setIdBox(cursor.getInt(cursor
				.getColumnIndex(COLUMN_ID_BOX)));

		boxInventory.setProductAmount(cursor.getInt(cursor
				.getColumnIndex(COLUMN_PRODUCT_AMOUNT)));
		boxInventory.setSentServerOk(cursor.getInt(cursor
				.getColumnIndex(COLUMN_IS_SENT_SERVER_OK)) == 1);
		boxInventory.setProductCode(cursor.getString(cursor
				.getColumnIndex(COLUMN_PRODUCT_CODE)));
		boxInventory
				.setDate(cursor.getLong(cursor.getColumnIndex(COLUMN_DATE)));

		return boxInventory;
	}

	public final boolean isTableExist()
	{
		open();

		boolean isExist = false;
		Cursor cursor = _database.rawQuery(
				"select DISTINCT tbl_name from sqlite_master where tbl_name = '"
						+ TABLE_NAME + "'", null);
		isExist = cursor != null && cursor.getCount() > 0;

		cursor.close();
		close();

		return isExist;
	}
}
